function serialize(val) {
  return JSON.stringify(val)
}

function deserialize(val) {
  if (typeof val !== 'string') {
    return undefined
  }
  try {
    return JSON.parse(val)
  } catch (e) {
    return val || undefined
  }
}

function insertArray(arr, val, compare) {
  const index = arr.findIndex(compare)
  if (index === 0) return
  arr.unshift(val)
}

function deleteFromArray(arr, compare) {
  const index = arr.findIndex(compare)
  if (index > -1) arr.splice(index, 1)
}

export function save(item, key, compare) {
  const items = deserialize(localStorage.getItem(key)) || []
  insertArray(items, item, compare)
  localStorage.setItem(key, serialize(items))
  return items
}

export function remove(key, compare) {
  const items = deserialize(localStorage.getItem(key)) || []
  deleteFromArray(items, compare)
  localStorage.setItem(key, serialize(items))
  return items
}

export function load(key) {
  return deserialize(localStorage.getItem(key)) || []
}

export function saveAll(items, key) {
  localStorage.setItem(key, serialize(items))
}
